<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar" :style="{top: statusBarHeight + 'px'}">
      <view class="search-container">
        <view class="search-input">
          <uni-icons type="search" color="#999" size="20"></uni-icons>
          <input 
            type="text" 
            v-model="searchParams.name" 
            placeholder="输入医院名称" 
            @confirm="handleSearch"
            @input="handleInputChange"
            @focus="handleFocus"
            :focus="isSearching"
          />
        </view>
        <!-- 城市选择器或取消按钮 -->
        <picker 
          v-if="!isSearching"
          mode="selector" 
          :range="cityOptions" 
          @change="onCityChange"
          class="city-picker"
        >
          <view class="picker-content">
            <text>{{ currentCity || '选择城市' }}</text>
            <text class="iconfont icon-arrow-down"></text>
          </view>
        </picker>
        <text 
          v-else 
          class="cancel-btn"
          @click="cancelSearch"
        >取消</text>
      </view>
    </view>

    <!-- 医院列表 -->
    <scroll-view 
      class="hospital-list" 
      scroll-y 
      :style="{top: statusBarHeight + 120 + 'px'}"
    >
      <view class="result-list">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
          <view class="loading-icon"></view>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 医院列表 -->
        <view 
          v-for="(hospital, index) in hospitals" 
          :key="index" 
          class="result-item hospital-item"
          @click="goToHospitalDetail(hospital)"
        >
          <view class="hospital-avatar">
            <image :src="config.staticUrl + (hospital.imgUrl || '/static/default-hospital.png')" mode="aspectFill"></image>
          </view>
          <view class="hospital-info">
            <view class="hospital-header">
              <text class="hospital-name">{{ hospital.name }}</text>
              <text class="hospital-level">{{ hospital.hospitalGrade || '二级医院' }}</text>
            </view>
            <view class="hospital-address">
              <text class="address">{{ hospital.address || '暂无地址信息' }}</text>
            </view>
            <view class="hospital-intro">
              <text>{{ hospital.snapshot || '暂无医院介绍' }}</text>
            </view>
          </view>
          <text class="iconfont icon-arrow-right arrow-right"></text>
        </view>

        <!-- 无结果提示 -->
        <view v-if="showNoResult" class="no-result">
          <text>暂无医院数据</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { listHospital } from '@/api/hospital'
import { getToken } from '@/utils/auth'
import config from '@/config'

export default {
  data() {
    return {
      statusBarHeight: 20,
      hospitals: [],
      loading: false,
      showNoResult: false,
      searchParams: {
        name: '',
        city: ''
      },
      currentCity: '',
      cityOptions: ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '南京'],
      config: config,
      isSearching: false // 新增搜索状态标志
    }
  },
  created() {
    // 获取状态栏高度
    try {
      const windowInfo = uni.getWindowInfo()
      this.statusBarHeight = windowInfo.statusBarHeight
    } catch (error) {
      console.error('获取状态栏高度失败:', error)
      this.statusBarHeight = 20
    }
    
    // 检查登录状态
    if (!getToken()) {
      uni.showModal({
        title: '提示',
        content: '请先登录后再查看医院列表',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/login'
            })
          } else {
            uni.navigateBack()
          }
        }
      })
      return
    }
    
    this.loadHospitals()
  },
  methods: {
    async loadHospitals() {
      this.loading = true
      this.showNoResult = false
      try {
        const query = {
          pageNum: 1,
          pageSize: 100
        }
        
        // 添加搜索条件
        if (this.searchParams.name) {
          query.name = this.searchParams.name
        }
        if (this.searchParams.city) {
          query.city = this.searchParams.city
        }
        
        const res = await listHospital(query)
        
        if (res.code === 200) {
          this.hospitals = res.rows || res.data || []
          this.showNoResult = this.hospitals.length === 0
        } else {
          uni.showToast({
            title: res.msg || '获取医院列表失败',
            icon: 'none'
          })
          this.showNoResult = true
        }
      } catch (error) {
        console.error('获取医院列表失败:', error)
        uni.showToast({
          title: '获取医院列表失败',
          icon: 'none'
        })
        this.showNoResult = true
      } finally {
        this.loading = false
      }
    },
    onCityChange(e) {
      const index = e.detail.value
      this.currentCity = this.cityOptions[index]
      this.searchParams.city = this.currentCity
      this.loadHospitals()
    },
    handleSearch() {
      this.isSearching = true
      this.loadHospitals()
    },
    
    // 处理输入框内容变化
    handleInputChange() {
      if (!this.searchParams.name.trim()) {
        this.cancelSearch()
      }
    },
    
    // 处理输入框聚焦
    handleFocus() {
      this.isSearching = true
    },
    
    // 取消搜索
    cancelSearch() {
      this.searchParams.name = ''
      this.isSearching = false
      this.loadHospitals()
    },
    
    goToHospitalDetail(hospital) {
      uni.navigateTo({
        url: `/pages/medical/hospital-detail?id=${hospital.id}`,
        success: (res) => {
          res.eventChannel.emit('hospitalData', {
            id: hospital.id,
            hospitalName: hospital.name,
            hospitalLevel: hospital.hospitalGrade,
            address: hospital.address,
            introduction: hospital.snapshot,
            imgUrl: hospital.imgUrl,
            phone: hospital.telephone
          })
        }
      })
    }
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #F5F6FA;
}

.search-bar {
  position: fixed;
  left: 0;
  right: 0;
  height: 100rpx;
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx 0;
  background-color: #FFFFFF;
  z-index: 10;
     margin-top: -45px;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.search-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.search-input {
  flex: 1;
  height: 70rpx;
  background-color: #F5F6FA;
  border-radius: 35rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.search-input input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
  padding-left: 12rpx;
  background: transparent;
}

.city-picker {
  width: 160rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  background-color: #F5F6FA;
  border-radius: 35rpx;
}

.picker-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.picker-content text:first-child {
  margin-right: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.icon-arrow-down {
  color: #999999;
  font-size: 28rpx;
}

.cancel-btn {
  margin-left: 24rpx;
  font-size: 28rpx;
  color: #333; 
  white-space: nowrap;
}

.hospital-list {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
     margin-top: -120px;
  background-color: #F5F6FA;
}

.result-list {
  padding: 32rpx;
  padding-bottom: 32rpx;
}

.hospital-item {
  display: flex;
  align-items: center;
  padding: 32rpx;
  background-color: #FFFFFF;
  margin-bottom: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(30, 144, 255, 0.1);
  transition: all 0.3s ease;
}

.hospital-item:active {
  transform: scale(0.98);
  background-color: #F5F6FA;
}

.hospital-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 16rpx;
  overflow: hidden;
  margin-right: 24rpx;
  background-color: #f5f5f5;
}

.hospital-avatar image {
  width: 100%;
  height: 100%;
}

.hospital-info {
  flex: 1;
}

.hospital-header {
  display: flex;
  align-items: center;
  margin-bottom:12rpx;
}

.hospital-name {
  font-size: 34rpx;
  color: #333333;
  font-weight: bold;
  margin-right: 16rpx;
}

.hospital-level {
  font-size: 24rpx;
  color: #1E90FF;
  background-color: rgba(30, 144, 255, 0.1);
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
}

.hospital-address {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.address {
  font-size: 28rpx;
  color: #666666;
}

.hospital-intro {
  font-size: 26rpx;
  color: #999999;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.5;
}

.arrow-right {
  color: #CCCCCC;
  font-size: 32rpx;
  margin-left: 20rpx;
}

.no-result {
  padding: 100rpx 0;
  text-align: center;
  color: #999999;
  font-size: 28rpx;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-icon {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #1E90FF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>